package com.smit.livevideo.sample.fragment;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.smit.dvb.DVBServiceInfo;
import com.smit.dvb.jni.DVB;
import com.smit.dvb.scan.IScanCallback;
import com.smit.dvb.scan.ScanControl;
import com.smit.dvb.system.ISystemCallback;
import com.smit.dvb.system.SystemControl;
import com.smit.livevideo.R;
import com.smit.livevideo.sample.MyApplication;
import com.smit.livevideo.sample.controller.ScanServicesController;
import com.smit.livevideo.sample.util.SDKAPIUtil;
import com.smit.utils.LogUtil;
import com.smit.utils.StrUtil;

import java.io.InputStream;
import java.util.ArrayList;

/**
 * Created by smfang on 2015/11/24. 搜台Fragment，主要是显示搜台进度并控制搜台
 */
public class ScanServicesFragment extends BaseFragment implements IScanCallback, ISystemCallback, Handler.Callback {
    /**
     * 报告搜索频率
     */
    public static final int DVB_SCAN_START = 0;
    /**
     * 报告信号质量
     */
    public static final int DVB_SCAN_TUNER_LOCK = 1;
    /**
     * 报告搜索进度
     */
    public static final int DVB_SCAN_PROGRESS_CHANGED = 2;
    /**
     * 报告搜索到得节目
     */
    public static final int DVB_SCAN_SERVICES_FOUND = 3;
    /**
     * 搜索完成
     */
    public static final int DVB_SCAN_FINISH = 4;

    private static final String TAG = ScanServicesFragment.class.getSimpleName();
    private static final int MSG_REFRESH_VIEW_FLIPPER = 1001;
    private static final int MSG_START_SCAN_OPERATOR = 1002;

    private int pictures[]
            = {R.drawable.start_init_image_01, R.drawable.start_init_image_02, R.drawable.start_init_image_03,
                    R.drawable.start_init_image_04, R.drawable.start_init_image_05};

    private ArrayList<Bitmap> adBitmaps;
    private Handler handler;

    /** 广告显示序号 */
    private int adShowIndex = 0;
    private int scanProgress = 0;
    private int dvbStatusWhenStop = -1;
    private boolean isScanStop = true;

    private TextView channelCountTextView;
    private TextView progressPercentTextView;
    private ViewFlipper adDisplayViewFlipper;
    private Button stopScanButton;
    private LineProgressBar progressBar;

    private ForegroundColorSpan foregroundColorSpan = null;
    private StyleSpan styleSpan = null;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        LogUtil.debug(TAG, "onAttach~~~~");
        this.activity = activity;
        handler = new Handler(this);
        /* 注册回调 */
        SDKAPIUtil.getScanControl().addCallback(this);
        SDKAPIUtil.getSystemControl().addCallback(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        LogUtil.debug(TAG, "onResume~~~~");
        if (DVB.getInstance().isbDVBInitOk()) {
            if (isScanStop == true) {
                LogUtil.error(TAG, "onResume isScanStop = true");
                isScanStop = false;
                LogUtil.error(TAG, "onResume isScanStop = false");
            } else {
                LogUtil.error(TAG, "onResume isScanStop = false");
                return;
            }
            initSearch();
        } else {
            LogUtil.debug(TAG, "onResume DVBInitFinish false");
        }
    }

    private void initData() {
        adBitmaps = new ArrayList<Bitmap>();
        for (int i = 0; i < pictures.length; i++) {
            Bitmap btp = getBitmap(pictures[i]);
            if (btp != null) {
                adBitmaps.add(btp);
                ImageView imageView = new ImageView(activity);
                imageView.setImageBitmap(btp);
                adDisplayViewFlipper.addView(imageView);
            }
        }

        foregroundColorSpan = new ForegroundColorSpan(
                getResources().getColor(R.color.tv_search_progress_num_text_color));
        styleSpan = new StyleSpan(Typeface.BOLD);
    }

    private void initSearch() {
        LogUtil.debug(TAG, "initSearch~~~~");
        ScanServicesController.startSearch();
        /* 初始化显示 */
        updateChannelCountText(0);
        updateProgressText();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        LogUtil.debug(TAG, "onCreateView~~~~");
        View view = inflater.inflate(R.layout.fragment_searchprogress, container, false);
        adDisplayViewFlipper = (ViewFlipper) view.findViewById(R.id.start_init_viewflipper);
        channelCountTextView = (TextView) view.findViewById(R.id.search_progress_label1);
        progressPercentTextView = (TextView) view.findViewById(R.id.search_progress_label2);
        stopScanButton = (Button) view.findViewById(R.id.new_searchprogress_btn);
        progressBar = (LineProgressBar) view.findViewById(R.id.lineProgressBar);

        stopScanButton.requestFocus();
        stopScanButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                stopSearchProcess();
            }
        });
        /* 初始化广告图片数据 */
        initData();
        /* 广告切换 */
        handler.sendEmptyMessageDelayed(MSG_REFRESH_VIEW_FLIPPER, 9000);

        return view;
    }

    @Override
    public void onPause() { //这里是为了处理Home键退出的情况，正常这里是不会走的吧
        LogUtil.debug(TAG, "onPause~~~");
        if (isScanStop == false) {
            SDKAPIUtil.getScanControl().abortScan();
        }
        super.onPause();
    }

    @Override
    public void onStop() {
        LogUtil.debug(TAG, "onStop~~~");
        stopAdDisplay();
        SDKAPIUtil.getScanControl().removeCallback(this);
        SDKAPIUtil.getSystemControl().removeCallback(this);
        handler.removeCallbacksAndMessages(null);
        //还原之前的数据
        isScanStop = true;
        adShowIndex = 0;
        scanProgress = 0;
        scanProgress = 0;
        dvbStatusWhenStop = -1;

        for (int i = 0; i < adDisplayViewFlipper.getChildCount(); i++) {
            ImageView imageView = (ImageView) adDisplayViewFlipper.getChildAt(i);
            imageView.setImageDrawable(null);
            imageView = null;
        }

        for (Bitmap btp : adBitmaps) {
            if (!btp.isRecycled()) {
                btp.recycle();
                //                System.gc();
            }
        }

        progressBar.clearPointPicture();
        super.onStop();
    }

    /*
     * 0: 这里不处理，给activity来处理 1: 这里处理了，activity不处理，系统也不要处理（这里在listener中来做了） 2:
     * 这里不处理，也不让activity处理
     */

    /**
     * 0: 这里不处理，给activity来处理 1: 这里处理了，activity不处理，系统也不要处理（这里在listener中来做了） 2:
     * 这里不处理，也不让activity处理
     *
     * @param keyCode 键值
     * @param event   按键事件
     * @return int
     */
    public int onKeyDown(int keyCode, KeyEvent event) {
        LogUtil.debug(TAG, "onkeydown is in");
        return 1;
    }

    /**
     * DVB system初始化OK后的回调
     */
    public void onSystemInitOK() {
        LogUtil.debug(TAG, "onSystemInitOK~~~");
        if (isScanStop == true) { //这里会有一个问题，和onResume那边同时调用了。
            LogUtil.error(TAG, "onSystemInitOK isScanStop = true");
            isScanStop = false;
            LogUtil.error(TAG, "onSystemInitOK isScanStop = false");
        } else {
            LogUtil.error(TAG, "onSystemInitOK isScanStop = false");
            return;
        }
        initSearch();
    }

    /**
     * 开始搜台回调
     */
    public void onScanServicesStart() {
        LogUtil.debug(TAG, "onScanServicesStart~~~~~");
    }

    /**
     * 搜台锁频回调
     */
    public void onScanServicesTunerLock() {
        LogUtil.debug(TAG, "onScanServicesTunerLock~~~~~");
    }

    /**
     * 搜台回调报告错误
     */
    public void onScanServicesError() {
        LogUtil.debug(TAG, "onScanServicesError~~~~~");
    }

    /**
     * 搜台进度回调
     *
     * @param progress 设置的进度
     */
    public void onScanServicesProgress(int progress) {
        LogUtil.debug(TAG, "onScanServicesProgress~~~~~ progress = " + progress);
        scanProgress = progress;
        updateProgressText();
    }

    /**
     * 搜台结束调用
     */
    public void onScanServicesFinish() {
        LogUtil.debug(TAG, "onScanServicesFinish~~~~~");
        ScanServicesController.setLastPlayChannel();
        progressFinish();
    }

    /**
     * 停止搜台进度条
     */
    private void progressFinish() {
        stopAdDisplay();
        FragmentUtil.popAllBackStack(activity.getFragmentManager());
        MyApplication.getInstance().startLiveVideoActivity();
    }

    /**
     * 停止广告显示
     */
    public void stopAdDisplay() {
        LogUtil.debug(TAG, "stopAdDisplay is in");
        if (handler != null) {
            handler.removeMessages(MSG_REFRESH_VIEW_FLIPPER);
        }
    }

    /**
     * 更新广告显示
     */
    private void updateAdDisplay() {
        if (adShowIndex == pictures.length - 1) {
            adShowIndex = 0;
            adDisplayViewFlipper.setInAnimation(AnimationUtils.loadAnimation(getActivity(), R.anim.anim_left_in));
            adDisplayViewFlipper
                    .setOutAnimation(AnimationUtils.loadAnimation(getActivity(), R.anim.anim_left_out));
            adDisplayViewFlipper.setDisplayedChild(1);
            handler.sendEmptyMessageDelayed(MSG_REFRESH_VIEW_FLIPPER, 9000);
            return;
        } else {
            adDisplayViewFlipper.setInAnimation(AnimationUtils.loadAnimation(getActivity(), R.anim.anim_left_in));
            adDisplayViewFlipper
                    .setOutAnimation(AnimationUtils.loadAnimation(getActivity(), R.anim.anim_left_out));
            adDisplayViewFlipper.showNext();
            adShowIndex++;
        }
        handler.sendEmptyMessageDelayed(MSG_REFRESH_VIEW_FLIPPER, 9000);
    }

    /**
     * 获取图片，并设置图片大小
     *
     * @param resId 图片id
     * @return Bitmap
     */
    private Bitmap getBitmap(int resId) {
        InputStream is = this.getResources().openRawResource(resId);
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = false;
        options.inSampleSize = 1;
        options.inPurgeable = true;
        options.inInputShareable = true;
        Bitmap bitmap;

        try {
            bitmap = BitmapFactory.decodeStream(is, null, options);
            return bitmap;
        } catch (OutOfMemoryError e) {
            LogUtil.info(TAG, "getBitmap OutOfMemoryError");
        }
        return null;
    }

    /**
     * 停止搜台：1.在扫描运营商的时候停止；2.在搜台的时候停止
     */
    private void stopSearchProcess() {
        isScanStop = true;
        stopScanButton.setEnabled(false);
        SDKAPIUtil.getScanControl().abortScan();
    }

    /**
     * 设置搜台进度条
     *
     * @return int
     */
    private int updateProgress() {
        if (isScanStop == true) {
            return 0;
        }
        int pos = 0;
        if (scanProgress > 0) {
            pos = scanProgress * 2 / 10 + scanProgress * 8 / 10;
        } else {
            pos = scanProgress;
        }
        progressBar.setProgress(pos);
        return pos;
    }

    /**
     * 设置搜台文本提示
     */
    private void updateProgressText() {
        if (isScanStop == true) {
            return;
        }
        updateProgress();
        channelCountTextView.setText(getResources().getString(R.string.tips_search_progress_label1));
        if (progressPercentTextView.getVisibility() != View.VISIBLE) {
            progressPercentTextView.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 更新频道个数的UI
     * @param totalChannelCount 节目总个数
     */
    public void updateChannelCountText(int totalChannelCount) {
        String program = String.format(getResources().getString(R.string.tips_search_progress_label2),
                totalChannelCount);
        progressPercentTextView.setText(getSpanText(program));
    }

    /**
     * 搜台显示字符的演示设置，标签的颜色和数据的颜色不一样
     *
     * @param text 需要显示的文本
     * @return SpannableStringBuilder
     */
    private SpannableStringBuilder getSpanText(String text) {
        SpannableStringBuilder builder = new SpannableStringBuilder(text);
        int start = text.lastIndexOf("：") + 1;
        int end = text.length();
        if (start >= 0 && start < end) {
            builder.setSpan(styleSpan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            builder.setSpan(foregroundColorSpan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }

        return builder;
    }

    @Override
    public void handleScanCallbackMsg(int i, Object o) {
        LogUtil.debug(TAG, "handleScanCallbackMsg:" + i + " o:" + o);
        Message handlerMsg = handler.obtainMessage(i, o);
        handlerMsg.sendToTarget();
    }

    @Override
    public void handleSystemCallbackMsg(int i, Object o) {
        LogUtil.debug(TAG, "handleSystemCallbackMsg:" + i);
        Message handlerMsg = handler.obtainMessage(i, o);
        handlerMsg.sendToTarget();
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case ScanControl.MSG_SCAN_START:
                ScanServicesController.setDVBScaningStatus(true);
                ScanServicesController.setScanStatus(DVB_SCAN_START);
                onScanServicesStart();
                break;
            case ScanControl.MSG_SCAN_TUNER_LOCKED:
                ScanServicesController.setScanStatus(DVB_SCAN_TUNER_LOCK);
                onScanServicesTunerLock();
                break;
            case ScanControl.MSG_SCAN_PROGRESS_CHANGED:
                ScanServicesController.setScanStatus(DVB_SCAN_PROGRESS_CHANGED);
                ScanServicesController.setDVBScaningStatus(true);
                onScanServicesProgress(StrUtil.parseInt(msg.obj.toString()));
                break;
            case ScanControl.MSG_SCAN_SERVICES_FOUND:
                ScanServicesController.setScanStatus(DVB_SCAN_SERVICES_FOUND);
                updateChannelCountText(ScanServicesController.onScanServicesFound((DVBServiceInfo[]) msg.obj));
                break;
            case ScanControl.MSG_SCAN_FINISH:
                ScanServicesController.setScanStatus(DVB_SCAN_FINISH);
                ScanServicesController.setDVBScaningStatus(false);
                ScanServicesController.saveServicesInfoToDB();
                onScanServicesFinish();
                break;
            case ScanControl.MSG_SCAN_ERROR:
                onScanServicesError();
                break;
            case SystemControl.MSG_SYSTEM_INIT_OK:
                onSystemInitOK();
                break;

            case MSG_START_SCAN_OPERATOR:
                channelCountTextView.setText(R.string.tips_scan_operator_enironment);
                break;
            case MSG_REFRESH_VIEW_FLIPPER:
                updateAdDisplay();
                break;
            default:
                break;
        }
        return false;
    }
}
